import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:repair_pda/controller/login_controller.dart';
import 'package:repair_pda/pages/login/group_widget.dart';
import 'package:repair_pda/utils/navigator_utils.dart';
import 'package:repair_pda/utils/stringUtils.dart';
import 'package:repair_pda/widgets/cc_input.dart';
import 'package:repair_pda/widgets/cc_button.dart';

/**
 * 2025年6月21日 12:20:09
 * 登录页面
 */
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 添加焦点控制器
  final FocusNode _usernameFocus = FocusNode();
  final FocusNode _passwordFocus = FocusNode();

  bool loginEnable = false;
  String? username = '';
  String? password = '';

  @override
  Widget build(BuildContext context) {
    NavigatorUtils.updateContext(context);

    return Scaffold(
      body: MediaQuery.removePadding(
          context: context,
          removeBottom: true,// 移除底部系统padding
          child: Stack(children: [..._background(), _content()])
      )
    );
  }

  //#region 背景图片+蒙层
  _background() {
    return [
      Positioned.fill(child: Image.asset('images/login-bg1.jpg',fit: BoxFit.cover)),
      // 为上面一个元素添加蒙层
      Positioned.fill(child: Container(decoration: const BoxDecoration(color: Colors.black54)))
    ];
  }
  //#endregion

  //#region 页面元素
  /* 2025年7月13日 15:04:07 通过 deepseek 解决从登录页面跳转到主页时在 android9 闪屏的问题时注释下面代码
     主要为解决 ListView 导致的焦点问题
  _content() {
    return Positioned.fill(
      left: 25, right: 25,
      child: ListView(// 可拖拽移位
        children: [
          SizedBox(height: 100),
          const Text('账号密码登录', style: TextStyle(fontSize: 26, color: Colors.white),),
          SizedBox(height: 100),
          // 账号
          InputWidget(
            placeHolder: '请输入登录账号',
            focusNode: _usernameFocus,
            onFieldSubmitted:  (value) { // 添加提交回调
              FocusScope.of(context).requestFocus(_passwordFocus);
            },
            onChanged: (text){
              username = text;
              print('username:$username');
              print('userIsEmpty:${isEmpty(username)}');
              _isBtnEnable();// 设置登录按钮是否可用
            },),

          // 密码
          InputWidget(
            placeHolder: '请输入密码', isPwd: true,
            focusNode: _passwordFocus,
            onFieldSubmitted:  (value) { // 添加提交回调
              if(loginEnable) _login();
            },
            onChanged: (text){
            password = text;
              _isBtnEnable();
            }
          ),
          SizedBox(height: 50),
          // 调用函数几种方式：
          // onPressed: () => _login()
          // onPressed: _login        仅仅是函数名称
          LoginButton('登录', enable: loginEnable, onPressed: () => _login(),),
          SizedBox(height: 25),
          Align(
            alignment: Alignment.centerRight,
            child: InkWell(
              onTap: () => _gotoRegistration(),
              child: const Text('注册账号', style: TextStyle(color: Colors.white))
            ),

          )
        ]
      )
    );
  }
   */

  _content() {
    return Positioned.fill(left:25,right: 25,child:
      SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(height: 50),
            const Text('账号密码登录', style: TextStyle(fontSize: 26, color: Colors.white),),
            SizedBox(height: 25),
            // 账号
            CcInput(
              placeHolder: '请输入登录账号',
              focusNode: _usernameFocus,
              onFieldSubmitted:  (value) { // 添加提交回调
                FocusScope.of(context).requestFocus(_passwordFocus);
              },
              onChanged: (text){
                username = text;
                print('username:$username');
                print('userIsEmpty:${isEmpty(username)}');
                _isBtnEnable();// 设置登录按钮是否可用
              },),
            // 密码
            CcInput(
                placeHolder: '请输入密码', isPwd: true,
                focusNode: _passwordFocus,
                onFieldSubmitted:  (value) { // 添加提交回调
                  if(loginEnable) _login();
                },
                onChanged: (text){
                  password = text;
                  _isBtnEnable();
                }
            ),
            SizedBox(height: 20),

            GroupWidget(),
            // 调用函数几种方式：
            // onPressed: () => _login()
            // onPressed: _login        仅仅是函数名称
            //CcButton('登录', enable: loginEnable, onPressed: () => _login(),),
            SizedBox(height: 25),
            SizedBox(
              width: double.infinity, // 宽度充满父容器
              child: CcButton('登录', enable: loginEnable, onPressed: () => _login())
            ),
          ],
        ),
      )
    );
  }
  //#endregion

  //#region 登录按钮是否可用
  void _isBtnEnable(){
    bool enabled = true;
    if(isEmpty(username)) {
      enabled = false;
      print('username是空');
    }
    if(isEmpty(password)) {
      enabled = false;
      print('password是空');
    }
    setState(() {
      loginEnable = enabled;
      print('更新按钮状态为：$loginEnable');
    });
  }
  //#endregion

  //#region 登录
  void _login() async {
    final LoginController loginController = Get.put(LoginController());
    //TODO: 制作类似下面的请求登录逻辑
    Fluttertoast.showToast(
        msg: '请求登录',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );
    await loginController.performLogin('username', 'password', 'A', '中班');

    /*
    try{
      bool loginSuccess = await LoginDao.login(username: 'test', password: 'test');
      Fluttertoast.showToast(
          msg: '请求登录完毕:$loginSuccess',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
      );
      if(loginSuccess){
        print('登录成功');
      }
    }catch(e){
      print(e);
      Fluttertoast.showToast(
          msg: e.toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
      );
    }
    */
  }
  //#endregion

  //#region 跳转到注册页面，app 打开浏览器
  void _gotoRegistration(){}
  //#endregion

  @override
  void dispose() {
    _usernameFocus.dispose();
    _passwordFocus.dispose();
    super.dispose();
  }
}
